package com.sskj.b70.v.fragment;


import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.sskj.b70.R;
import com.sskj.b70.adapter.slimadapter.IViewInjector;
import com.sskj.b70.adapter.slimadapter.SlimAdapter;
import com.sskj.b70.adapter.slimadapter.SlimInjector;
import com.sskj.b70.common.Constants;
import com.sskj.b70.common.rxbus2.RxBus;
import com.sskj.b70.common.rxbus2.Subscribe;
import com.sskj.b70.common.rxbus2.ThreadMode;
import com.sskj.b70.m.StockCoinBean;
import com.sskj.b70.mvchelper.RefreshDataSource;
import com.sskj.b70.mvchelper.refresh.MVCSmartHelper;
import com.sskj.b70.p.fragment.MarketHangqingFragmentPst;
import com.sskj.b70.utils.ClickUtil;
import com.sskj.b70.utils.DisposUtil;
import com.sskj.b70.v.activity.MainActivity;
import com.sskj.b70.v.activity.MarketNewActivity;
import com.sskj.b70.v.base.BaseFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 行情列表
 * create by Hey at 2018/5/4 15:33
 */
public class MarketListHangqingFragment extends BaseFragment<MainActivity, MarketHangqingFragmentPst> {


    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private String code;
    private MVCSmartHelper<List<StockCoinBean>> mvcHelper;
    private SlimAdapter<StockCoinBean> slimAdapter;
    private HashMap<String, Integer> coinImg;
    private Map<String, Disposable> timeMap = new HashMap<>();

    /**
     * @param code ETH ,BTC,USDT
     * @return
     */
    public static MarketListHangqingFragment newInstance(String code) {
        Bundle args = new Bundle();
        MarketListHangqingFragment fragment = new MarketListHangqingFragment();
        args.putString(Constants.CODE, code);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_market_list_hangqing;
    }

    @Override
    public MarketHangqingFragmentPst getPresenter() {
        return new MarketHangqingFragmentPst();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWebSocketMessage(StockCoinBean.StockProductVOBean stockSocketBean) {
        Flowable.fromIterable(slimAdapter.getData())
                .filter(item -> item.getStockProductVO().getCode().equals(stockSocketBean.getCode()))
                .subscribe(item -> {
                    if (Double.valueOf(stockSocketBean.getPrice()) > Double.valueOf(item.getStockProductVO().getPrice())) {
                        stockSocketBean.setGreen(true);
                    } else {
                        stockSocketBean.setGreen(false);
                    }
                    stockSocketBean.setLight(true);
                    item.setStockProductVO(stockSocketBean);
                    slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(item));
                    DisposUtil.close(timeMap.get(item.getStockProductVO().getCode()));
                    Disposable subscribe = Flowable.timer(600, TimeUnit.MILLISECONDS)
                            .subscribeOn(Schedulers.newThread())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(i -> {
                                item.getStockProductVO().setLight(false);
                                slimAdapter.notifyItemChanged(slimAdapter.getData().indexOf(item));
                            });
                    timeMap.put(item.getStockProductVO().getCode(), subscribe);
                });
    }

    @Override
    public void initView() {
        coinImg = new HashMap<>();
        coinImg.put("BTC", R.mipmap.btc);
        coinImg.put("BCH", R.mipmap.bch);
        coinImg.put("ETC", R.mipmap.etc);
        coinImg.put("ETH", R.mipmap.eth);
        coinImg.put("LTC", R.mipmap.ltc);
        coinImg.put("EOS", R.mipmap.eos);
        coinImg.put("PSTR", R.mipmap.pstr);
        RxBus.getDefault().register(this);
        if (getArguments() != null) {
            code = getArguments().getString("code");
        }
        refreshLayout.setEnableAutoLoadMore(false);
        refreshLayout.setRefreshHeader(new MaterialHeader(getActivity()));
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
//        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
//                .setFirstDraw(false)
//        );
        initAdapter();
    }


    private void initAdapter() {
        slimAdapter = SlimAdapter.create().register(R.layout.recy_item_market, new SlimInjector<StockCoinBean>() {
            @Override
            public void onInject(StockCoinBean stock, IViewInjector injector) {
                injector.text(R.id.tv_sale_price, stock.getStockProductVO().getPrice())
                        .text(R.id.tv_type, stock.getName().split("/")[0])

                        .text(R.id.tv_unit, stock.getName().split("/")[1])
                        .image(R.id.iv_coin, coinImg.get(stock.getCode().split("/")[0])==null?R.mipmap.btc:coinImg.get(stock.getCode().split("/")[0]));
                double change = 0;
                try {
                    change = Double.valueOf(stock.getStockProductVO().getChange());
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                if (change > 0) {
                    injector.background(R.id.tv_condition, R.drawable.shape_bull_cyan_blue_rect);
                } else if (change == 0) {
                    injector.backgroundColor(R.id.tv_condition, getResources().getColor(R.color.gray_cf));
                } else {
                    injector.background(R.id.tv_condition, R.drawable.shape_bull_red_rect);
                }
                injector.text(R.id.tv_condition, stock.getStockProductVO().getChangeRate());
                if (stock.getStockProductVO().isLight()) {
                    if (stock.getStockProductVO().isGreen()) {
                        injector.backgroundColor(R.id.tv_sale_price, ContextCompat.getColor(getActivity(), R.color.bull_cyan_blue));
                    } else {
                        injector.backgroundColor(R.id.tv_sale_price, ContextCompat.getColor(getActivity(), R.color.bull_red));
                    }
                } else {
                    injector.backgroundColor(R.id.tv_sale_price, ContextCompat.getColor(getActivity(), R.color.bull_white));

                }


                ClickUtil.click(injector.findViewById(R.id.market_item), () -> {
                    MarketNewActivity.start(mActivity, stock.getCode());
                });
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        RefreshDataSource<StockCoinBean> refreshDataSource = new RefreshDataSource<StockCoinBean>() {
            @Override
            public Flowable<List<StockCoinBean>> loadData() {
                RxBus.getDefault().send(Constants.PUSH_SOCKET_START);
                return mPresenter.getData(code);
//                        .map(stockCoinBeans -> {
//                            StockCoinBean stock = stockCoinBeans.get(0);
//                            StockLevel stockLevel = new StockLevel();
//                            stockLevel.setCode(stock.getCode());
//                            stockLevel.setName(stock.getName());
//                            stockLevel.setLeverage(stock.getLever());
//                            stockLevel.setPrice(stock.getPublishPrice());
//                            stockLevel.setMinDealNum(stock.getContractMin());
//                            stockLevel.setShouPer(stock.getDealFee());
//                            stockLevel.setSlidingScalePrice(stock.getSlidingScalePrice());
//                            stockLevel.setSpread(stock.getSpread());
//                            stockLevel.setStopLoss((float) stock.getStopLoss());
//                            stockLevel.setStopProfit((float) stock.getStopProfit());
//                            mActivity.stockLevel = stockLevel;
//                            RxBus.getDefault().send(Constants.FIRST_GET_LEVEL_STOCK);
//                            return stockCoinBeans;
//                        });
            }
        };
        mvcHelper = new MVCSmartHelper<>(refreshLayout);
        mvcHelper.setDataSource(refreshDataSource);
        mvcHelper.setAdapter(slimAdapter);
        mvcHelper.refresh();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unregister(this);
    }
}
